# coding: utf8


"""
This file is part of PeerTool, a web application for collaborative
decision-making (Copyrighted, 2009-2010, Ellis & Grant, Inc.)
Developed by Michael F. Ellis <michael.f.ellis@gmail.com>.  
License: AGPL v3
PeerTool comes with ABSOLUTELY NO WARRANTY.
"""                
@auth.requires_login()
def index():
    """
    Creates and handles results from a form that displays all the user's
    current invitations and acceptances.  User can alter acceptance status on
    one or more problems or simply click one of the problem links to begin
    working on a particular problem. 
    """

    dbi = db.invitations                                ## shorter name

    ## query that works on GAE 
    rows = db(dbi.email==auth.user.email).select()   
    rdict = {}                                          ## will hold row objects 
                                                        ## keyed by invitation id
    for r in rows:
        rdict[r.id] = r                                 ## Save for later.
        p = db(db.problems.id==r.problemid).select()    ## Find in problems table.
        assert(len(p)==1)                               ## Enforced by other code
        r['problems'] = p[0]                            ## Add to r

    rows = sorted(rows, 
        key=lambda r: r.problems.timestamp, 
        reverse=True)                                   ## Most recently changed
                                                        ## first.

    #debug("\n".join(
    #    [str(r.problems.timestamp) for r in rows]))
    ## We want new invites before accepted problems 
    ## before rejected problems
    rows = sorted(rows, 
        key=lambda r: -1 if r.accepted==None else 0 
        if r.accepted==True else 1)

    kls = "invitations"                         # CSS class for all 
                                                # elements in form.
    tbl = TABLE(_class=kls)
    problemicon = URL(r=request, 
        c='static', f="rubik32.png")

    tbl.append(TR(IMG(_src=problemicon),        # Table header
                    B(T("From")), 
                    B(T("Accept?")), 
                    B(T("Participants")), 
                    B(T("Last Activity")),
                    _class=kls))

    for r in rows:                              # Table rows.
        rp = r.problems                         # shorter name

        if (rp.isembryo and                     # Don't show invitations 
            rp.creatorid != auth.user.id):      # to gestating problems
            continue                            # user didn't create.
                                                
        id = "cbx%d"%r.id                       # Checkbox
        label = rp.label                        # Short description
        acc = r.accepted
        if acc == True:                         # If accepted,
            label = A(XML(label),_class=kls,         # link to response page.
                _href=URL(r=request, 
                c='respond', f='index', 
                args=[r.problemid],
                ),
                )
        elif acc == False:
            label = XML("<del>%s</del>"%label)  # strikethrough font

        else:                                   # new invitation
            label = XML(label)                  # plain font

        tbl.append(TR(                          # Fill in the row
            label,
            r.invitedby,
            INPUT(_type="checkbox",_id=id, _name=id,
                _class=kls, value=acc,_value='on'),
            rp.participants,
            prettydate(rp.timestamp,T=T))
            )

    tbl.append(TR("",INPUT(_type="submit")))
    form = FORM(tbl)    

    if form.accepts(request.vars,session):      # web2py magic
        for k,v in form.vars.iteritems():
            if k.startswith('cbx'):             # i.e. checkbox

                ## update participation status as needed
                id = int(k[3:])
                accepted = dbi[id].accepted
                r = rdict[id]
                if v  == 'on' and not accepted:
                    dbi[id] = dict(accepted='True')
                    problem = loadProblem(r.problemid)
                    problem.addTeamMember(auth.user.id)
                    mergeadditions(problem,problemid=r.problemid)
                elif v != 'on' and accepted:
                    dbi[id] = dict(accepted='False')
                    problem = loadProblem(r.problemid)
                    problem.delTeamMember(auth.user.id)
                    updateProblem(r.problemid,problem)

        ## redirect to self so that the form will be updated 
        ## based on latest commitments to db
        redirect(URL(r=request,c='choose',f='index'))

    elif form.errors:
        response.flash = T('form has errors')
    return dict(form=form, kls=kls)   
